package com.bidevalution.business.job;

import com.bidevalution.business.factory.StepJobJdbcFactory;
import com.bidevalution.business.function.FunctionCalculator;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.BeEvalutionDetailSummary;
import com.bidevalution.dao.entity.BeEvalutionSummary;
import com.bidevalution.dao.entity.BeSectionStep;
import com.bidevalution.dao.entity.BeSectionStepJob;
import com.bidevalution.support.context.Constant;
import com.bidevalution.support.util.OConvertUtil;
import com.bidevalution.support.util.StringUtil;
import com.google.common.collect.Maps;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import com.qtp.core.util.OConvertUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 评审项明细计算环节审核结果（少数服从多数)；
 *
 * @author daizhifeng
 * @version V2.0
 * @date 2019年9月30日 下午5:07:17
 */
public class StepDetailComputeResultNewJob implements StepJobJdbcFactory {
    private JdbcTemplateService jdbcTemplateService;

    @Override
    public Boolean execute(BeSectionStepJob beSectionStepJob, String submitCode, String expertId, String layouCode)
            throws Exception {
        String[] params = StringUtils.delimitedListToStringArray(beSectionStepJob.getJobContent(), "|");
        //c1,c2|c3 c1和c2表示计算的字段 c3表示审核结果字段
        String[] columnCodes = StringUtils.delimitedListToStringArray(params[0], ",");

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("sectionStepId", beSectionStepJob.getSectionStepId());
        paramMap.put("sectionId", beSectionStepJob.getSectionId());
        paramMap.put("submitCode", submitCode);
        List<String> columnValueList;
        List<Map<String, Object>> dataList;
        //结果汇总
        Map<String, Object> resultMap = Maps.newHashMap();
        Map<String, Object> env;
        RowMapper<BeSectionStep> rm1 = BeanPropertyRowMapper.newInstance(BeSectionStep.class);
        //获取标段环节数据
        BeSectionStep beSectionStep = jdbcTemplateService.selectForObject(" select\n" +
                "    seq_id, section_id, step_code, step_name, parent_code, order_num, step_url, related_step_code, \n" +
                "    related_layout_code, related_column_code, related_step_id, create_time, update_time,load_function" +
                "    from be_section_step where seq_id=:sectionStepId", paramMap, rm1);
        paramMap.put("relatedStepId", beSectionStep.getRelatedStepId());
        //删除已存在的汇总结果
        jdbcTemplateService.update(" DELETE FROM be_evalution_summary WHERE section_step_id=:relatedStepId and submit_code=:submitCode and is_del=0", paramMap);
        //删除已存在的评审项目明细汇总结果
        jdbcTemplateService.update(" DELETE FROM be_evalution_detail_summary WHERE section_step_id=:sectionStepId and submit_code=:submitCode and is_del=0", paramMap);

        //获取评审项id
        List<Map<String, Object>> methodIdList = this.jdbcTemplateService.selectForList(
                "SELECT tech_JSMethodID methodId, tech_Name techName FROM td_technology a left join be_section_info b on a.tech_ProjectID = b.td_projectId where b.seq_id=:sectionId", paramMap);
        //获取单位列表
        List<String> enterpriseIdList = this.jdbcTemplateService.selectForList(
                "select DISTINCT enterprise_id enterpriseId from be_evalution_outcome where section_step_id=:relatedStepId and is_del='0'", paramMap, String.class);

        //未通过原因
        StringBuilder unPassedReason = new StringBuilder();
        //获取单位列表
        for (String enterpriseId : enterpriseIdList) {
            if (enterpriseId != null && !StringUtils.isEmpty(enterpriseId)) {
                //最终结果是否通过
                String isPassed = "1";
                unPassedReason.delete(0, unPassedReason.length());
                paramMap.put("enterpriseId", enterpriseId);
                resultMap.clear();
                //获取评审项列表
                for (Map<String, Object> method : methodIdList) {
                    if (method != null && !StringUtils.isEmpty(method.get("methodId"))) {
                        String methodId = OConvertUtils.getString(method.get("methodId"));
                        paramMap.put("methodId", methodId);
                        //获取评审数据
                        dataList = this.jdbcTemplateService.selectForList(
                                "select c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17,c18,c19,c20" +
                                        " from be_section_expert_info b left join be_evalution_outcome a on a.expert_id = b.seq_id and a.section_step_id=:sectionStepId and a.is_del='0' and a.enterprise_id=:enterpriseId and a.m1=:methodId" +
                                        " where b.is_avoid = 0 and b.section_id=:sectionId",
                                paramMap);
                        //将评审结果设置为通过
                        for (String columnCode : columnCodes) {
                            String isSinglePassed = "1";
                            if (dataList != null && dataList.size() > 0) {
                                columnValueList = new ArrayList<>();
                                for (Map<String, Object> data : dataList) {
                                    columnValueList.add(OConvertUtils.getString(data.get(columnCode),"1"));
                                }
                                env = new HashMap<>();
                                env.put("columnValues", StringUtils.collectionToDelimitedString(columnValueList, ","));
                                //单列是否通过，1 表示通过，0 表示未通过
                                isSinglePassed = FunctionCalculator.computeAviator("maxFrequencyOfArray(columnValues)", env);
                            }
                            resultMap.put(columnCode, isSinglePassed);
                            if ("0".equals(isSinglePassed)) {
                                //单位最终结果，有一个评审项不通过则不通过
                                isPassed = isSinglePassed;
                                unPassedReason.append("在【").append(beSectionStep.getStepName()).append("】中【").append( OConvertUtils.getString(method.get("techName"))).append("】未通过评审；");
                            }
                        }
                        //保存明细汇总表
                        BeEvalutionDetailSummary beEvalutionDetailSummary = new BeEvalutionDetailSummary();
                        BeanUtils.populate(beEvalutionDetailSummary, resultMap);
                        beEvalutionDetailSummary.setSeqId(IdsUtil.uuid());
                        beEvalutionDetailSummary.setMethodId(methodId);
                        beEvalutionDetailSummary.setEnterpriseId(enterpriseId);
                        beEvalutionDetailSummary.setSectionId(beSectionStepJob.getSectionId());
                        beEvalutionDetailSummary.setSectionStepId(beSectionStepJob.getSectionStepId());
                        beEvalutionDetailSummary.setSectionStepCode(beSectionStep.getStepCode());
                        beEvalutionDetailSummary.setSubmitCode(submitCode);
                        beEvalutionDetailSummary.setCreateTime(DateUtil.now());
                        beEvalutionDetailSummary.setUpdateTime(DateUtil.now());
                        jdbcTemplateService.insertBean("insert into be_evalution_detail_summary (seq_id, section_step_id, section_step_code,section_id, submit_code, enterprise_id, method_id, c1, c2, c3, c4, c5,c6, c7, c8, c9,c10, c11, c12, c13, \n" +
                                "      c14, c15, c16, c17, c18, c19, c20, create_time, update_time, is_del) values (:seqId, :sectionStepId, :sectionStepCode, :sectionId, \n" +
                                "      :submitCode, :enterpriseId, :methodId, :c1, :c2, :c3, :c4, :c5,:c6, :c7, :c8, :c9, :c10, :c11, :c12, :c13, :c14, :c15, :c16, :c17, :c18, :c19, :c20, " +
                                "	   :createTime, :updateTime, 0)", beEvalutionDetailSummary);
                    }
                }
                resultMap.put(params[1],isPassed);
                //保存汇总记录
                BeEvalutionSummary beEvalutionSummary = new BeEvalutionSummary();
                BeanUtils.populate(beEvalutionSummary, resultMap);
                beEvalutionSummary.setSeqId(IdsUtil.uuid());
                beEvalutionSummary.setEnterpriseId(enterpriseId);
                beEvalutionSummary.setSectionId(beSectionStep.getSectionId());
                beEvalutionSummary.setSectionStepId(beSectionStep.getRelatedStepId());
                beEvalutionSummary.setSectionStepCode(beSectionStep.getRelatedStepCode());
                beEvalutionSummary.setIsPassed(Integer.valueOf(isPassed));
                beEvalutionSummary.setUnpassedReason(unPassedReason.toString());
                beEvalutionSummary.setSubmitCode(submitCode);
                jdbcTemplateService.insertBean("insert into be_evalution_summary (seq_id, section_step_id, section_step_code,section_id, submit_code, enterprise_id, c1, c2, c3, c4, c5,c6, c7, c8, c9,c10, c11, c12, c13, \n" +
                        "      c14, c15, c16, c17, c18, c19, c20, is_passed, unpassed_reason, create_time, update_time, is_del) values (:seqId, :sectionStepId, :sectionStepCode, :sectionId, \n" +
                        "      :submitCode, :enterpriseId, :c1, :c2, :c3, :c4, :c5,:c6, :c7, :c8, :c9, :c10, :c11, :c12, :c13, :c14, :c15, :c16, :c17, :c18, :c19, :c20, " +
                        "	   :isPassed, :unpassedReason, now(), now(), 0)", beEvalutionSummary);

            }
        }

        return true;
    }

    @Override
    public void setJdbcTemplateService(JdbcTemplateService jdbcTemplateService) {
        this.jdbcTemplateService = jdbcTemplateService;
    }

}
